package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.BehaviorService;
import com.heima.common.constants.LikesConstants;
import com.heima.common.constants.ReadBehaviorConstans;
import com.heima.common.constants.UnLikesBehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dto.LikesBehaviorDto;
import com.heima.model.behavior.dto.ReadBehaviorDto;
import com.heima.model.behavior.dto.UnLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
@Slf4j
public class BehaviorServiceImpl implements BehaviorService {

    @Autowired
    private CacheService cacheService;

    private final static String LIKE = "LIKE";

    /**
     * 点赞行为
     * 0 点赞
     * 1 取消点赞
     *
     * @param likesBehaviorDto
     * @return
     */
    @Override
    public ResponseResult likesBehavior(LikesBehaviorDto likesBehaviorDto, HttpServletRequest request) {
        //1.校验参数
        if (likesBehaviorDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        String userId = getUserId(request);
        if ("0".equals(userId)) {
            return ResponseResult.errorResult(509,"请登录后再点赞！");
        }

        //3.判断点赞状态，点赞则存，取消点赞则删除
        Short operation = likesBehaviorDto.getOperation();
        if (operation == null) {
            log.info("点赞参数不存在");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //将数据存入Redis的hash中
        cacheService.hPut(LikesConstants.USER_LIKE_BEHAVIOR + "-" + userId, likesBehaviorDto.getArticleId()+"", JSON.toJSONString(likesBehaviorDto));



        /*Map<String, String> map = new HashMap<>();
        map.put(likesBehaviorDto.getArticleId()+"", likesBehaviorDto.getArticleId()+"");
        map.put(userId+"", userId+"");
        cacheService.hPutAll(likesBehaviorDto.getOperation()+"", map);*/

        /*if (operation.equals(LikesConstants.LIKE)) {
            Map<String, String> map = new HashMap<>();
            map.put(likesBehaviorDto.getArticleId()+"", likesBehaviorDto.getArticleId()+"");
            map.put(userId+"", userId+"");
            cacheService.hPutAll(likesBehaviorDto.getOperation()+"", map);
        } else if (operation.equals(LikesConstants.NOT_LIKE)) {
            cacheService.hDelete(userId+"");
        }*/


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 获取用户id
     * @param request
     * @return
     */
    private String getUserId(HttpServletRequest request) {
        //2.获取用户id
        return request.getHeader("userId");
    }

    /**
     * 是否喜欢功能
     * @param unLikesBehaviorDto
     * @param request
     * @return
     */
    @Override
    public ResponseResult unLikesBehavior(UnLikesBehaviorDto unLikesBehaviorDto, HttpServletRequest request) {
        //1.校验参数
        if (unLikesBehaviorDto == null || unLikesBehaviorDto.getType() == null) {
            log.info("参数无效");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        String userId = getUserId(request);
        if ("0".equals(userId)) {
            return ResponseResult.errorResult(509,"请登录后再试！");
        }


        //2.存入Redis
        cacheService.hPut(UnLikesBehaviorConstants.USER_UNLIKE_BEHAVIOR+userId,unLikesBehaviorDto.getArticleId()+"",JSON.toJSONString(unLikesBehaviorDto));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 阅读行为
     *
     * @param readBehaviorDto
     * @param request
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto readBehaviorDto, HttpServletRequest request) {
        //1.校验参数
        if (readBehaviorDto == null) {
            log.info("参数无效");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.存入Redis
        String key = ReadBehaviorConstans.READ_BEHAVIOR + "-" + getUserId(request);
        //获取文章id
        Long articleId = readBehaviorDto.getArticleId();
        if (cacheService.exists(key)) {
            //有则将阅读量自增
            String json = (String) cacheService.hGet(key, articleId + "");
            if (StringUtils.isNotEmpty(json)) {
                ReadBehaviorDto behaviorDto = JSON.parseObject(json, ReadBehaviorDto.class);
                readBehaviorDto.setCount(behaviorDto.getCount()+1);
                cacheService.hDelete(key, articleId + "");
                cacheService.hPut(key,articleId+"", JSON.toJSONString(readBehaviorDto));
            }
        } else {
            //没有直接存
            cacheService.hPut(key,articleId+"", JSON.toJSONString(readBehaviorDto));
        }

        /*//key=read-behavior-userId
        //value=articleId 文章id
        //score=count 阅读数量
        //获取到阅读量
        String key = ReadBehaviorConstans.READ_BEHAVIOR+getUserId(request);
        if (cacheService.exists(key)){
            //存在将阅读量自增
            String count = cacheService.get(key);
            cacheService.zIncrementScore(key, readBehaviorDto.getArticleId()+"", readBehaviorDto.getCount()+1);
        } else {
            //不存在直接存
            cacheService.zAdd(key,readBehaviorDto.getArticleId()+"", readBehaviorDto.getCount());
        }*/

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
